#include "Render/RenderManager.h"



#include "GfxDriver/GfxDriver.h"
#include "Render/RenderQueue.h"

namespace Orca {

	//--------------------------------------------------------------------------
	TRenderManager::TRenderManager(IGfxDriver *gfxDriver) {

	}

	//--------------------------------------------------------------------------
	TRenderManager::~TRenderManager() {

	}

	//--------------------------------------------------------------------------
	void TRenderManager::render(unsigned short startQueueId, unsigned short stopQueueId) {

		const size_t cnt = mRQList.size();

		size_t startIdx, stopIdx;

		for(size_t i = 0; i < cnt; ++i) {

			TRenderQueue *rq = mRQList[i];

			stopIdx = i;

			if(rq->getId() <= startQueueId) startIdx = i;
			if(rq->getId() > stopQueueId) break;
		}

		for(size_t i = startIdx; i < stopIdx; ++i)
			mRQList[i]->render(mGfxDriver);
	}

	//--------------------------------------------------------------------------
	void TRenderManager::registerRenderQueue(
		  unsigned short id
		, IRenderQueueSorter *sorter) {

		TRQMapping::iterator iter = mRQMapping.find(id);

		if( iter != mRQMapping.end() )
			return;

		mRQMapping[id] = new TRenderQueue(id, sorter);

		_refreshRQList();
	}

	//--------------------------------------------------------------------------
	void TRenderManager::unregisterRenderQueue(unsigned short id) {

		TRQMapping::iterator iter = mRQMapping.find(id);

		if( iter == mRQMapping.end() )
			return;

		delete iter->second;
		mRQMapping.erase(iter);

		_refreshRQList();
	}

	//--------------------------------------------------------------------------
	TRenderQueue* TRenderManager::getRenderQueue(unsigned short id) {

		TRQMapping::iterator iter = mRQMapping.find(id);

		if( iter == mRQMapping.end() )
			return NULL;

		return iter->second;
	}

	//--------------------------------------------------------------------------
	void TRenderManager::_refreshRQList() {

		mRQList.clear();

		TRQMapping::iterator curr = mRQMapping.begin();
		const TRQMapping::iterator end = mRQMapping.end();

		while(curr != end) {

			mRQList.push_back(curr->second);
			++curr;
		}
	}

	//--------------------------------------------------------------------------
}